package org.common.utils.net.netty.http;

import org.common.utils.net.netty.NettyServer;
import org.common.utils.net.netty.http.core.*;
import org.common.utils.net.netty.http.intercept.HttpIntercept;
import org.common.utils.net.netty.http.intercept.HttpInterceptPool;
import org.common.utils.net.netty.http.listener.HttpListener;
import org.common.utils.net.netty.http.listener.HttpListenerPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.Executors;

/**
 * 一个基于netty的http服务器
 * @author zhouzhibing
 * @date 2025/11/20 20:05
 */
public class NettyHttpServer {

    private static final Logger log = LoggerFactory.getLogger(NettyHttpServer.class);
    /**
     * 端口
     */
    private final int port;
    /**
     * net服务器
     */
    private final NettyServer server;
    /**
     * Http的路由池。
     */
    private final RouterPool routerPool;
    /**
     * 拦截器池
     */
    private final HttpInterceptPool eventPool;
    /**
     * 监听器池
     */
    private final HttpListenerPool listenerPool;
    /**
     * HTTP 请求处理类
     */
    private final HttpHandler httpHandler;

    /**
     * 创建NettyHttpSerer, 支持HTTP请求。
     * @param packageName 包名
     * @param port 端口
     */
    public NettyHttpServer(String packageName , int port) {
        this.port = port;
        this.routerPool = new RouterPool(packageName);
        this.eventPool = new HttpInterceptPool();
        this.listenerPool = new HttpListenerPool();
        this.httpHandler = new HttpHandler(routerPool, eventPool, listenerPool, Executors.newVirtualThreadPerTaskExecutor());
        HttpInitializer initializer = new HttpInitializer(httpHandler);
        this.server = new NettyServer(initializer);
    }

    /**
     * 启动
     */
    public void start() {
        this.server.start(this.port);
        log.info("NettyHttpServer: start success , Port [{}]" , port);
    }

    /**
     * 添加拦截器
     * @param intercept 拦截对象
     */
    public void addIntercept(HttpIntercept intercept) {
        eventPool.addInterceptor(intercept);
    }

    /**
     * 移除拦截器
     * @param intercept 拦截对象
     */
    public void removeIntercept(HttpIntercept intercept) {
        eventPool.removeInterceptor(intercept);
    }


    /**
     * 添加监听器
     * @param batch 批量监听器
     */
    public void addListener(HttpListener.Batch batch) {
        listenerPool.addListener(batch);
    }

    /**
     * 添加监听器
     * @param listener 监听器
     */
    public void addListener(HttpListener<?> listener) {
        listenerPool.addListener(listener);
    }

    /**
     * 移除监听器
     * @param listener 监听器
     */
    public void removeListener(HttpListener<?> listener) {
        listenerPool.removeInterceptor(listener);
    }

    /**
     * 打印异常，并在页面上显示异常信息。
     */
    public void openExceptionShow(){
        httpHandler.openExceptionShow();
    }

    /**
     * 关闭异常打印，不会在页面上显示异常信息。
     */
    public void closeExceptionShow(){
        httpHandler.closeExceptionShow();
    }
}
